﻿#include "book_info.h"
#include "ui_book_info.h"
#include "lib/sql_mgr.h"
#include"dlg_bookadd.h"
#include"dlg_bookrb.h"
#include <QMessageBox>
Book_Info::Book_Info(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Book_Info)
{
    ui->setupUi(this);
    ui->tableView->setModel(&m_Model);//绑定模型
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
}

Book_Info::~Book_Info()
{
    delete ui;
}



    void Book_Info::initPage(QString strCondtion)
    {

        //查询数据库并且显示
        auto l = sql_mgr::getInstance()->getBooks(strCondtion);
        m_Model.clear();
        m_Model.setHorizontalHeaderLabels(QStringList{"ISBN","Book_Name","Author","Avail_Num","Storage_Num"});
        for(int i = 0;i<l.size();i++)
        {
            QList<QStandardItem*> items;
            for(int j = 0;j<l[i].size();j++)
            {
                items.append(new QStandardItem(l[i][j]));
            }

            m_Model.appendRow(items);
        }
    }




void Book_Info::on_btn_log_clicked()
{
    dlg_bookadd dlg;
    dlg.exec();
    initPage();
}


void Book_Info::on_btn_borrow_clicked()
{
    int r = ui->tableView->currentIndex().row();
    if(r<0)
    {
        return;
    }
    auto id = m_Model.item(r,0)->text();
    auto cnt = m_Model.item(r,3)->text().toInt();
    if(cnt<=0)
    {
        QMessageBox::information(nullptr,"Message","Failure::No Avail_Num");
        return;
    }
    dlg_bookrb dlg;
    dlg.setBookId(id);
    int ret = dlg.exec();
    QMessageBox::information(nullptr,"Message",ret?"Success":"Failure");
    if(ret)
    {
        initPage();
    }
}


void Book_Info::on_lineEdit_textChanged(const QString &arg1)
{
    QString strCond = QString("where book_name like '%%1%' or author like '%%1%' ").arg(arg1);//书名与作者联想
    initPage(strCond);
}

